package com.lin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lin.entity.Subject;
import com.lin.entity.vo.Classification;
import com.lin.entity.vo.ClassificationTwo;
import com.lin.mapper.SubjectMapper;
import com.lin.service.SubjectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author 霖霖
 * @since 2022-12-09
 */
@Service
public class SubjectServiceImp extends ServiceImpl<SubjectMapper, Subject> implements SubjectService {

    @Override
    public List<Classification> getClassification() {
        QueryWrapper<Subject> subjectQueryWrapper = new QueryWrapper<>();
        subjectQueryWrapper.eq("parent_id", "0");
        List<Subject> subjectsOne = baseMapper.selectList(subjectQueryWrapper);
        QueryWrapper<Subject> queryWrapper = new QueryWrapper<>();
        queryWrapper.ne("parent_id", "0");
        List<Subject> subjectsTwo = baseMapper.selectList(queryWrapper);

        List<Classification> finalList = new ArrayList<>();
        for (Subject subject : subjectsOne) {
            Classification oneBean = new Classification();
            BeanUtils.copyProperties(subject, oneBean);
            oneBean.setKey(subject.getId());

            ArrayList<ClassificationTwo> classificationTwos = new ArrayList<>();
            for (int i = subjectsTwo.size() - 1; i >= 0; i--) {
                Subject subjectTwo = subjectsTwo.get(i);
                if (oneBean.getKey().equals(subjectTwo.getParentId())) {
                    ClassificationTwo twoBean = new ClassificationTwo();
                    BeanUtils.copyProperties(subjectTwo, twoBean);
                    twoBean.setKey(subjectTwo.getId());
                    subjectsTwo.remove(i);
                    classificationTwos.add(twoBean);
                }
            }
            oneBean.setChildren(classificationTwos);
            finalList.add(oneBean);
        }

        return finalList;
    }

    @Override
    public boolean removeSubject(String id) {
        Subject subject = baseMapper.selectById(id);
        if (subject != null && "0".equals(subject.getParentId())) {
            QueryWrapper<Subject> subjectQueryWrapper = new QueryWrapper<>();
            subjectQueryWrapper.eq("parent_id", id).or().eq("id", id);
            return baseMapper.delete(subjectQueryWrapper) > 0;
        } else {
            return baseMapper.deleteById(id) > 0;
        }
    }
}
